const app = getApp();
const { post } = require('../../utils/request');

Page({
  data: {
    hasLogin: false,
    userInfo: null,
    bmi: '',
    plan: null,
    isLoading: false
  },

  onLoad() {
    this.setData({
      hasLogin: app.globalData.hasLogin,
      userInfo: app.globalData.userInfo
    });
    
    if (this.data.userInfo) {
      this.calculateBMI();
    }
  },

  onShow() {
    if (this.data.hasLogin !== app.globalData.hasLogin) {
      this.setData({
        hasLogin: app.globalData.hasLogin,
        userInfo: app.globalData.userInfo
      });
      
      if (app.globalData.userInfo) {
        this.calculateBMI();
      }
    }
  },

  calculateBMI() {
    const { height, weight } = this.data.userInfo;
    if (height && weight) {
      const heightInMeters = height / 100;
      const bmi = (weight / (heightInMeters * heightInMeters)).toFixed(1);
      this.setData({ bmi });
    }
  },

  async generatePlan() {
    if (!this.data.hasLogin) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    try {
      this.setData({ isLoading: true });
      wx.showLoading({
        title: '生成中',
      })
      const res = await post('/plan/generate');
      wx.hideLoading()
      if (res.code === 0) {
        // 将AI返回的文本按段落分割并整理成对象
        const planText = res.data.plan;
        const sections = planText.split('\n\n');
        
        const plan = {
          weeklyPlan: sections.find(s => s.includes('每周')) || '',
          intensity: sections.find(s => s.includes('强度')) || '',
          precautions: sections.find(s => s.includes('注意事项')) || '',
          expectedResults: sections.find(s => s.includes('预期')) || '',
          dietSuggestions: sections.find(s => s.includes('饮食')) || ''
        };

        this.setData({ plan });
      } else {
        throw new Error(res.message);
      }
    } catch (error) {
      wx.showToast({
        title: error.message || '生成计划失败',
        icon: 'none'
      });
    } finally {
      this.setData({ isLoading: false });
    }
  },

  navigateToLogin() {
    wx.navigateTo({
      url: '/pages/login/login'
    });
  }
}); 